package com.cf.r1003_ak;

import java.io.*;
import java.util.Arrays;

public class d {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StreamTokenizer in = new StreamTokenizer(br);
        PrintWriter out = new PrintWriter(System.out);
        in.nextToken(); int t = (int) in.nval;
        while (t-- > 0) {
            in.nextToken(); int n = (int) in.nval;
            in.nextToken(); int m = (int) in.nval;
            int[][] arr = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    in.nextToken(); arr[i][j] = (int) in.nval;
                }
            }
            Arrays.sort(arr, (o1, o2) -> {
                long sum1 = Arrays.stream(o1).sum();
                long sum2 = Arrays.stream(o2).sum();
                if (sum1 == sum2) {
                    return o2[0] - o1[0];
                }
                return Long.compare(sum2, sum1);
            });
            out.println(compute(arr));
        }
        out.close();
        out.close();
        br.close();
    }

    static long compute(int[][] arr) {
        long sum = 0;
        long s = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                s += arr[i][j];
                sum += s;
            }
        }
        return sum;
    }

}
